<?php

namespace addons\booking\model;

use app\common\library\Auth;
use think\Model;


class Collect extends Model
{

    // 表名
    protected $name = 'booking_collect';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'status_text'
    ];


    public function getTypeList()
    {
        return ['0' => __('Type 0'), '1' => __('Type 1'), '2' => __('Type 2')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 添加收藏/取消收藏
     * @param int    $user_id
     * @param string $type
     * @param int    $source_id
     * @return false|int
     */
    public static function addOrCancel($user_id, $type, $source_id)
    {
        $data = self::where('user_id', $user_id)->where('type', $type)->where('source_id', $source_id)->find();
        //不存在，添加收藏
        if (!$data) {
            return (new self)->save([
                'type'      => $type,
                'user_id'   => $user_id,
                'source_id' => $source_id
            ]);
        }
        if ($data->status == 1) { //已收藏，为取消
            $data->status = 0;
        } else { //已取消，添加收藏
            $data->status = 1;
        }
        return $data->save();
    }

    /**
     * 渲染收藏
     *
     * @param mixed  $list
     * @param int    $user_id
     * @param string $type
     * @return void
     */
    public static function render($list, $user_id, $type)
    {
        $data = self::where('user_id', $user_id)->where('type', $type)->where('status', 1)->select();
        $newData = [];
        foreach ($data as $item) {
            $newData[$item['source_id']] = $item['status'];
        }
        foreach ($list as $res) {
            $res->isCollect = isset($newData[$res['id']]) ?? $newData[$res['id']]['status'];
        }
    }

    /**
     * 判断是否收藏
     * @param int  $type      类型 0=房间 1=商品
     * @param int  $source_id 来源ID
     * @param null $user_id   会员ID
     * @return int
     */
    public static function isCollect($type, $source_id, $user_id = null)
    {
        $user_id = is_null($user_id) ? Auth::instance()->id : $user_id;
        if (!$user_id) {
            return false;
        }
        $result = Collect::where('user_id', $user_id)
            ->where('type', $type)
            ->where('source_id', $source_id)
            ->where('status', 1)->find();
        return !!$result;
    }

    /**
     * 收藏列表
     *
     * @param array $param
     * @return \think\Paginator
     */
    public static function tableList($param)
    {
        $pageNum = 15;
        if (isset($param['num']) && !empty($param['num'])) {
            $pageNum = $param['num'];
        }
        $withArr = [];
        if (isset($param['type'])) {
            switch ($param['type']) {
                case 1:
                    $withArr['Goods'] = function ($query) {
                        $query->field('id,name,image,price,intro,market_price');
                    };
                    break;
                default:
                    $withArr['House'] = function ($query) {
                        $query->field('id,name,images,market_price,price');
                    };
            }
        }

        $list = self::with($withArr)
            ->field('id,type,source_id,user_id,status,createtime')
            ->where(function ($query) use ($param) {

                $query->where('status', 1);

                if (isset($param['user_id']) && !empty($param['user_id'])) {
                    $query->where('user_id', $param['user_id']);
                }
                if (isset($param['type']) && $param['type'] != '') {
                    $query->where('type', $param['type']);
                }

            })->order('createtime desc')->paginate($pageNum);


        return $list;
    }

    public function House()
    {
        return $this->belongsTo('House', 'source_id', 'id', [], 'LEFT');
    }

    public function Goods()
    {
        return $this->belongsTo('Goods', 'source_id', 'id', [], 'LEFT');
    }
}
